<template>
  <el-dialog
    v-model="diagVisable"
    title="手机验证登录"
    width="30%"
    center
    align-center
     @close="cancel()"
  >
    <el-form
      ref="formRef"
      :model="form"
      label-width="100px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <el-form-item label="手机号" prop="tel">
        <el-input v-model="form.tel" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-row>
          <el-col :span="11">
            <el-input v-model="form.code" type="text" autocomplete="off" />
          </el-col>
          <el-col :span="6"></el-col>
          <el-col :span="7"
            ><el-button
              style="width: 100px"
              type="primary"
              ref="btn"
              :disabled="isDisabled"
              @click="getVlCode()"
              >获取验证码</el-button
            >
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit"> 登录 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { sendSms, verification } from "@/api/user";
import { ElMessage } from "element-plus";

export default {
  props: ["diagVisable"],
  // 数据源
  data() {
    // 验证手机的规则
    var checkMobile = (rule, value, callback) => {
      // 手机号正则表达式
      const regMobile =
        /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
      if (regMobile.test(value)) {
        // 合法的手机号
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    };
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 邮箱正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (regEmail.test(value)) {
        // True 合法的邮箱
        return callback();
      }
      callback(new Error("请输入合法的邮箱"));
    };
    return {
      form: {
        tel: "",
        code: "",
      },
      count: 60,
      isDisabled: false,
      rules: {
        tel: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: checkMobile,
            trigger: "blur",
          },
        ],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
      },
      timer: null,
    };
  },
  //生命周期函数---
  mounted() {},
  //基本方法
  methods: {
    getVlCode() {
      this.$refs.formRef.validateField(["tel"], (valid, fields) => {
        if (valid) {
          if (this.isDisabled) return;
          this.isDisabled = true;
          this.timer = setInterval(() => {
            this.count--;
            this.$refs.btn.$el.innerText = `${this.count}s后重新发送`;
            if (this.count < 0) {
              clearInterval(this.timer);
              this.count = 60;
              this.isDisabled = false;
              this.$refs.btn.$el.innerText = `重新获取`;
            }
          }, 1000);
          sendSms(this.form.tel).then((res) => {
            if (res.code == 200) {
              ElMessage({
                type: "success",
                message: "发送成功",
              });
            } else {
              ElMessage({
                type: "info",
                message: "发送失败",
              });
            }
          });
        }
      });
    },
    submit() {
      this.$refs.formRef.validate((valid, fields) => {
        if (valid) {
          verification(this.form.tel, this.form.code).then((res) => {
            if (res.code == 200) {
              let token = res.data.token;
              this.$store.commit("setUserMessage", res.data.user);
              window.sessionStorage.setItem("token", token);
              if (res.data.user.role == "admin") {
                this.$router.push({
                  path: "/admin/userManage",
                });
              } else {
                this.$router.push({
                  path: "/space",
                });
              }
              ElMessage({
                message: "欢迎回来!",
                type: "success",
              });
              this.cancel();
            } else {
              ElMessage({
                type: "error",
                message: "验证码错误或已过期",
              });
            }
          });
        }
      });
    },
    cancel() {
      this.$refs.formRef.resetFields();
      this.$emit("childsolt");
    },
  },
  beforeUnmount() {
    if (this.timer) window.clearInterval(this.timer);
  },
};
</script>

<style scoped>
</style>